<?php
/**
 * Product categories controlles
 * 
 * @author Konstantin Shamko <konstantin.shamko@gmail.com> 
 * @version 0.0.1
 * @copyright  Copyright (c) 2009 Konstantin Shamko
 * @package Products Module
 * @license  New BSD License
 *
 */
class products_CategoriesController extends Bel_Controller{

	/**
	 * Product categories model
	 *
	 * @var Models_ProductCategories
	 */
	private $_categories;
	
	/**
	 * Category node max level to show in categories tree
	 *
	 * @var integer
	 */
	private $_max_level_to_show = 3;
	
	/**
	 * Initialization
	 *
	 */
	public function init(){
		parent::init();
		$this->_categories = new Models_ProductCategories();
	}
	
	/**
	 * Disaplays subcategories of selected category. If category has no subcategories
	 * then producs of selected category are displayed
	 *
	 */
	public function indexAction(){
		$cat_id = $this->_request->getParam('cat_id');
		
		if($cat_id){//if category was selected
			$node = $this->_categories->getNodeInfo($cat_id);
			$this->_seo->setTitle($node->category_name);
		}else{//default state when category was not selected
			$nodes = $this->_categories->getTree('category_level=1');
			$node = $nodes[0];
			$cat_id = $node->category_id;
			$this->_seo->setTitle('Categories');
		}	

		$this->_seo->setDescription($node->category_description);
		$this->_seo->setKeywords($node->category_keywords);
		
		//get selected category parent to show breadcrumbs
		$parents = $this->_categories->getParentBranch($cat_id,'category_level>1');
		$this->view->assign('parents',$parents);
		
		if(($node->category_right_key-$node->category_left_key)==1){//has no subcategories
			$this->_forward('index','products');
		}else{//has subcategories				
			$categories = $this->_categories->getTreeBranch($cat_id,'category_level='.($node->category_level+1));				
			$this->view->assign('categories',$categories);				
		}	
		$this->view->display('products/catalog/catalog_list.tpl');
	}

	/**
	 * Displayes categories tree. Max cetegory node level is 3 and
	 * defined by $_max_level_to_show variable. Tree is expandable/collapsable 
	 *
	 */
	public function showtreeAction(){
		$request=$this->_request->getParams();
		$tree = $this->_categories->getTree('category_level=2');
		
		if(isset($request['cat_id'])){
			$expandedBranch = $this->_categories->getAncestorsAndSiblings($request['cat_id'], $this->_max_level_to_show);

			if($expandedBranch){
				$result = array();
				foreach ($tree as $node){						
					if($expandedBranch[0]->category_id==$node->category_id){
						foreach($expandedBranch as $branchNode){
							$result[] = $branchNode;
						}
					}else{
						$result[] = $node;
					}
				}				
				
				$tree = $result;
				unset($result);
			}
			$this->view->assign('current',$request['cat_id']);
		}
		
		$this->view->assign('tree',$tree);
		$this->view->display('products/catalog/catalog_tree.tpl');
	}
}